<script setup lang="ts">
import {
  defineModel,
  ref,
  useTemplateRef,
  reactive,
  watch,
  nextTick
} from "vue";
import { isMobile } from "@/utils/utils";

defineProps({
  classList: {
    type: Array,
    default: () => []
  }
});
const emits = defineEmits(["submit"]);
const dialogVisible = defineModel({ default: false });
const editFormRef = useTemplateRef("editFormRef");
const classId = defineModel("classId");
const submitLoading = ref(false);
const editForm = ref({
  text: ""
});
const editFormRules = reactive({
  text: [{ required: true, message: "请输入学生姓名", trigger: "blur" }]
});

watch(dialogVisible, async visible => {
  if (!visible) return;
  await nextTick();
  editFormRef.value.clearValidate();
  editForm.value.text = "";
});

const submitHandle = async function () {
  await editFormRef.value.validate(valid => {
    console.log(valid);
    if (!valid) return;

    submitLoading.value = true;
    const spaceReg = /^\s+|\s+$/g;
    const stuTextArr = editForm.value.text
      .split("\n")
      .map(item => item.replace(spaceReg, ""))
      .filter(item => item);
    emits("submit", { class_id: classId.value, data: stuTextArr });
    dialogVisible.value = false;

    setTimeout(() => {
      submitLoading.value = false;
    }, 1000);
  });
};
</script>

<template>
  <ElDialog
    v-model="dialogVisible"
    title="文本导入"
    width="520"
    :close-on-click-modal="false"
    :fullscreen="isMobile()"
  >
    <ElForm ref="editFormRef" :model="editForm" :rules="editFormRules">
      <ElFormItem label="所属班级">
        <ElSelect
          v-model="classId"
          class="class-select"
          placeholder="请选择班级"
        >
          <ElOption
            v-for="item in classList"
            :key="item.class_id"
            :label="item.class_name"
            :value="item.class_id"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem prop="text">
        <ElInput
          v-model="editForm.text"
          type="textarea"
          :rows="15"
          placeholder="每行输入一个学生姓名，例如：
张三
李四
王五"
        />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="submitHandle" :loading="submitLoading">
          确定
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<style scoped lang="scss"></style>
